#include "stdafx.h"
#include "ui.h"
#include "simd.h"
#include "glm/glm.hpp"
#include "rays.h"
#include "math.h"

#include <cmath>
#include "sphere.h"



int _tmain(int argc, _TCHAR* argv[])
{	
	
	RayStream rs(4000 / 8 * 2);

	auto ui = ui::init();
	unsigned char i = 0;
	int frame = 0;
	int start_time = SDL_GetTicks();
	
	auto proj = proj_matrix(ui.w, ui.h);
	
	GenerateEyeRaysInfo info;
	{
		info.delta_position_per_pixel = delta_position_per_pixel(45, ui.w / (float)ui.h, 1, 1000, vec2(ui.w, ui.h));
		info.eye_position = vec3(0, 0, 0);
		info.frustrum = frustrum(proj, vec2(ui.w, ui.h));
		info.rays = &rs;
		info.rays->blocks_per_row = ui.w / 8;
		info.rays_view.block_offset = 0;
		info.rays_view.block_count = info.rays->blocks_per_row * 2;
	}
	
	
	IntersectRayWithSpheresInfo intersectRayWithSpheresInfo;
	{
		intersectRayWithSpheresInfo.rays = info.rays;
		intersectRayWithSpheresInfo.spheres = new SphereStream(1);
		{
			intersectRayWithSpheresInfo.spheres->origins.set_block(0, as_v3block(vec3(0, 0, 0)));
			intersectRayWithSpheresInfo.spheres->radii.set_block(0, as_f32block(5));
		}
		intersectRayWithSpheresInfo.sphere_blocks_count = 1;
		intersectRayWithSpheresInfo.intersection_stream_offset = 0;
		intersectRayWithSpheresInfo.intersections = new RayIntersectionStream(1000);
		intersectRayWithSpheresInfo.debug = new f32stream(1000);
	}
	while(true)
	{				
		if(ui::process_events(ui)) break;
		ui::begin_frame(ui);
		frame++;
		info.rays->blocks_per_row = ui.w / 8;
		for(int r = 0; r < ui.h; r += 2)
		{			
			info.y_bounds.min = r;
			info.y_bounds.max = r + 2;
			intersectRayWithSpheresInfo.ray_blocks_count = ceil(ui.w / 8.0) * 2;
			generate_eye_rays(info);
			intersect_rays_with_spheres(intersectRayWithSpheresInfo);

			int y = r;
			

			for(int y = r; (y < (r + 2)) & (y < ui.h); y++)
			{
				for(int x_block_index = 0; x_block_index < ui.w; x_block_index++)
				{
					auto color = intersectRayWithSpheresInfo.intersections->position
						.y[(y - r) * (ui.w) + x_block_index];
					ui::set_color(ui, x_block_index, y, color * 255, 0, 0);		
					
				}
			}
		}	
		
		ui::update_time_per_frame(ui, (float)(SDL_GetTicks() - start_time) / frame);
		ui::end_frame(ui);
	}
	
	return 0;
	
}
